/*
 * navi.cpp - EmbedContainer for Navit
 *
 * Copyright (C) 2010-2011 Serge Begger
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "navi.h"
#include "naviX11.h"



navi::navi(QWidget *parent) :
    QX11EmbedContainer(parent)
{
    setGeometry(QRect(1, 1, 798, 498));    
    process = new QProcess(this);
    connect(process, SIGNAL(readyReadStandardOutput()),this,SLOT(readStOut()));
    connect(process, SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(changeState(QProcess::ProcessState)));
}

navi::~navi()
{
    if (process->isOpen())
    {
        process->terminate();
        delete process;
    }
}

bool navi::init()
{
    QString wId = QString::number(this->winId());
    setenv("NAVIT_XID", wId.toAscii(), 1);

    QString path = "/usr/bin/navit";
    if (!QFile::exists(path)) {
        path = "/usr/local/bin/navit";
        if (!QFile::exists(path)) {
            myMessage message(0);
            message.exec(0,"Navit not found!!! Install it..");
            return false;
        }
    }
    qcarpclog log(this);
    log.append("navi","state - execute");
    process->start(path);
    QTimer::singleShot(4000, this, SLOT(naviIsStarted()));
    return true;
}

void navi::naviIsStarted() {
    if (process->state() != QProcess::Running) {
        qcarpclog log(this);
        log.append("navi","state - "+QString().number(process->state()));
        log.append("navi","error - "+QString().number(process->error()));
        this->close();
    }
}

void navi::changeState(QProcess::ProcessState state) {
    if (state == QProcess::Running) {
       long winId = 0; int c = 0;
       while(winId == 0) {
           winId = getWinID("Navit");
           c++;
           if (c == 1000) break;
        }
        if (winId == 0) {
            this->close();
        }
        this->embedClient(winId);
    } else if (state == 0) {
        this->close();
    }
}

void navi::readStOut() {
    QByteArray data = process->readAllStandardOutput();
    if (data.startsWith("'Fix the speech tag in navit.xml to let navit say:'")) {
        emit speechText(data.mid(data.indexOf("say:'")+7));
    }
}
